import { Col, Divider, Row, Tabs, Tag, Tooltip, message, Space, Tree, Empty, Switch } from 'antd';
import {
  postApiUser as Create,
  putApiUserById as Update,
  getApiUserCheckIsRedundant,
} from '@/services/furion-cms/user';
import { AlipayOutlined, ClusterOutlined, DownOutlined, FileProtectOutlined, FolderOutlined, IdcardOutlined, InfoCircleOutlined, KeyOutlined, QqOutlined, TagOutlined, UserOutlined, WechatOutlined } from '@ant-design/icons';
import ProForm, {
  ModalForm,
  ProFormRadio,
  ProFormSwitch,
  ProFormText
} from '@ant-design/pro-form';
import React, { useEffect, useRef, useState } from 'react';

import { CheckCard } from '@ant-design/pro-card';
import ProList from '@ant-design/pro-list';

import type { ModalProps } from 'antd';
import type {
  ProFormInstance,
} from '@ant-design/pro-form';
import { getApiRoleAll as GetRoles } from '@/services/furion-cms/role';
import styles from '../index.less';
import { useIntl } from 'umi';
import { AvatarUpload } from "@/components/CustomUpload";
import {
  getApiOrganizationTree as GetOrgs,
} from '@/services/furion-cms/organization';
import type { DataNode } from 'antd/lib/tree';
import { Md5 } from 'ts-md5';

const { TabPane } = Tabs;

interface DetailProps {
  modalVisible?: boolean;
  recored?: API.UserDetailDto;
  onUpdate?: () => void;
  onVisibleChange: (visit: boolean) => void;
  modalProps?: Omit<ModalProps, 'visible'>;
}

const DetailViewer: React.FC<DetailProps> = (props) => {
  const { modalVisible, onUpdate, onVisibleChange, modalProps, recored } = props;
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  // 绑定一个 ProFormInstance 实例
  const formRef = useRef<ProFormInstance<API.UserDetailDto>>();

  const [activeKey, setActiveKey] = useState<string>('base');
  const [roleList, setRoleList] = useState<API.RoleDto[]>([]);
  const [treeData, setTreeData] = useState<DataNode[]>([]);

  const formattedDataHandle = (inputs: API.OrgDto[]): DataNode[] => {
    return inputs.map(m => ({ icon: <FolderOutlined />, title: m.name!, key: m.id!, children: formattedDataHandle(m.children ?? []) }));
  }

  useEffect(() => {
    if (modalVisible) {
      (async () => {
        try {
          const { data } = await GetRoles();
          setRoleList(data!);
          // 查找默认角色
          const defaultRoles = data?.filter(t => t.isDefault).map(m => m.id!);
          if (recored?.id === undefined) {
            formRef.current?.setFieldsValue({
              roles: defaultRoles
            });
          }

        } catch (error) {

        }
      })();

      (async () => {
        try {
          const { data } = await GetOrgs({});
          setTreeData(formattedDataHandle(data ?? []));
        } catch (error) {

        }
      })();
      setActiveKey('base');
    }
  }, [modalVisible]);// eslint-disable-line react-hooks/exhaustive-deps

  const finishHandle = (values: any) => {
    console.log('finishHandle', values);
    // 提交成功处理
    const successHandle = () => {
      // 清空数据
      message.success('人员信息保存成功');
      onUpdate?.();
      return true;
    }

    if (recored?.id) {
      // 更新
      return Update({ id: recored?.id }, { ...values })
        .then(successHandle);
    }
    else {
      // 创建
      return Create({ ...values })
        .then(successHandle);
    }
  };

  const remoteValidator = async (field: string, value: any, tabKey: string) => {
    try {
      const { success, errorMessage } = await getApiUserCheckIsRedundant({
        fieldname: field,
        fieldvalue: value,
        ignoreid: recored?.id
      }, { skipErrorHandler: true });
      if (!success) {
        // 更新TabPaneKey
        setActiveKey(tabKey);
        return Promise.reject(errorMessage);
      }
      return Promise.resolve();
    }
    catch (err) {
      return Promise.reject(err);
    }
  }

  const handlePassportTypeIcon = (type: number) => {
    const typeIcons = [
      <KeyOutlined className={styles.passportTypeIcon} />,
      <WechatOutlined className={styles.passportTypeIcon} />,
      <QqOutlined className={styles.passportTypeIcon} />,
      <AlipayOutlined className={styles.passportTypeIcon} />
    ];
    return typeIcons[type];
  }

  return (
    <ModalForm<API.UserDetailDto>
      title={recored?.id ? intl.formatMessage({
        id: 'pages.user.detail.title.edit',
        defaultMessage: '编辑用户'
      }) : intl.formatMessage({
        id: 'pages.user.detail.title.create',
        defaultMessage: '创建用户'
      })}
      modalProps={{
        destroyOnClose: true,
        width: 660,
        maskClosable: false,
        bodyStyle: {
          paddingLeft: 0
        },
        ...modalProps
      }}
      visible={modalVisible}
      initialValues={recored}
      onFinish={finishHandle}
      formRef={formRef}
      onVisibleChange={onVisibleChange}
    >
      <Tabs tabPosition="left"
        activeKey={activeKey}
        className={styles.userSettings}
        onChange={setActiveKey}>
        <TabPane tab={<><UserOutlined /> {intl.formatMessage({
          id: 'pages.user.detail.base',
          defaultMessage: '基本信息'
        })}</>} key="base">
          <Row wrap={false} gutter={20}>
            <Col flex="auto">
              <ProFormText
                name="nickName"
                label={intl.formatMessage({
                  id: 'pages.user.detail.input.nickName',
                  defaultMessage: '用户昵称'
                })}
                tooltip={intl.formatMessage({
                  id: 'pages.user.detail.input.nickName.tip',
                  defaultMessage: '用户昵称不允许重复'
                })}
                placeholder={intl.formatMessage({
                  id: 'pages.user.detail.input.nickName.placeholder',
                  defaultMessage: '请输入您要使用的昵称'
                })}
                validateTrigger={['onChange', 'onBlur']}
                required
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'pages.user.detail.input.nickName.rules',
                      defaultMessage: '用户昵称必填'
                    }),
                    validateTrigger: 'onChange',
                    validator: (rule, value) => {
                      if (!value) {
                        // 更新TabPaneKey
                        setActiveKey('base');
                        return Promise.reject(rule.message);
                      }
                      return Promise.resolve();
                    }
                  },
                  {
                    validator: (_, value) => {
                      if (value) {
                        return remoteValidator('NickName', value, 'base');
                      }
                      else {
                        return Promise.resolve();
                      }
                    },
                    validateTrigger: 'onBlur'
                  }
                ]}
              />
              <ProFormRadio.Group
                name="gender"
                label={intl.formatMessage({
                  id: 'pages.user.detail.input.gender',
                  defaultMessage: '性别'
                })}
                options={[
                  {
                    label: intl.formatMessage({
                      id: 'pages.user.detail.input.gender.male',
                      defaultMessage: '男'
                    }),
                    value: 1,
                  },
                  {
                    label: intl.formatMessage({
                      id: 'pages.user.detail.input.gender.female',
                      defaultMessage: '女'
                    }),
                    value: 2,
                  },
                ]}
              />
              <ProFormText
                name="email"
                label={intl.formatMessage({
                  id: 'pages.user.detail.input.email',
                  defaultMessage: '电子邮件'
                })}
                placeholder=""
                validateTrigger={['onChange', 'onBlur']}
                rules={[
                  {
                    pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
                    message: intl.formatMessage({
                      id: 'pages.user.detail.input.email.rules',
                      defaultMessage: '电子邮件格式错误!'
                    }),
                    validateTrigger: 'onChange'
                  },
                  {
                    validator: (_, value) => {
                      if (value) {
                        return remoteValidator('Email', value, 'base');
                      }
                      else {
                        return Promise.resolve();
                      }
                    },
                    validateTrigger: 'onBlur'
                  }
                ]}
              />
              <ProFormText
                name="phoneNumber"
                label={intl.formatMessage({
                  id: 'pages.user.detail.input.phoneNumber',
                  defaultMessage: '手机号'
                })}
                placeholder=""
                validateTrigger={['onChange', 'onBlur']}
                rules={[
                  {
                    pattern: /^1\d{10}$/,
                    message: intl.formatMessage({
                      id: 'pages.user.detail.input.phoneNumber.rules',
                      defaultMessage: '手机号格式错误!'
                    }),
                    validateTrigger: 'onChange'
                  },
                  {
                    validator: (_, value) => {
                      if (value) {
                        return remoteValidator('PhoneNumber', value, 'base');
                      }
                      else {
                        return Promise.resolve();
                      }
                    },
                    validateTrigger: 'onBlur'
                  }
                ]}
              />
              <ProFormSwitch name="enable" label={intl.formatMessage({
                id: 'pages.user.detail.input.enable',
                defaultMessage: '是否启用'
              })} />
            </Col>
            <Col>
              <ProForm.Item name="avatar" valuePropName="src"
                noStyle>
                <AvatarUpload onChange={fileUri => formRef.current?.setFieldsValue({
                  avatar: fileUri
                })} />
              </ProForm.Item>
            </Col>
          </Row>
        </TabPane>
        {recored?.id === undefined && <TabPane tab={<><KeyOutlined /> {intl.formatMessage({
          id: 'pages.user.detail.account',
          defaultMessage: '登录账号'
        })}</>} key="account" forceRender={true}>
          <ProFormText
            name="account"
            label={intl.formatMessage({
              id: 'pages.user.detail.input.account',
              defaultMessage: '账号'
            })}
            tooltip={intl.formatMessage({
              id: 'pages.user.detail.input.account.tip',
              defaultMessage: '账号长度为5~20位'
            })}
            placeholder={intl.formatMessage({
              id: 'pages.user.detail.input.account.placeholder',
              defaultMessage: '请输入登录系统的账号'
            })}
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              {
                required: true,
                pattern: /^[a-zA-Z\d]\w{3,19}[a-zA-Z\d]$/,
                message: intl.formatMessage({
                  id: 'pages.user.detail.input.account.rules',
                  defaultMessage: '账号长度在5~20位，且只能是字母，数字，下划线组成'
                }),
                validateTrigger: 'onChange',
                validator: (rule, value) => {
                  if (!rule.pattern?.test(value) || !value) {
                    // 更新TabPaneKey
                    setActiveKey('account');
                    return Promise.reject(rule.message);
                  }
                  return Promise.resolve();
                }
              },
              {
                validator: (_, value) => {
                  if (value) {
                    return remoteValidator('Account', value, 'account');
                  }
                  return Promise.resolve();
                },
                validateTrigger: 'onBlur'
              }
            ]}
          />
          <ProFormText.Password
            label={intl.formatMessage({
              id: 'pages.user.detail.input.password',
              defaultMessage: '密码'
            })}
            name="password"
            placeholder={intl.formatMessage({
              id: 'pages.user.detail.input.password.placeholder',
              defaultMessage: '请输入登录密码'
            })}
            rules={[
              {
                required: true,
                pattern: /^[a-zA-Z0-9]{6,22}$/,
                message: intl.formatMessage({
                  id: 'pages.user.detail.input.password.rules',
                  defaultMessage: '密码长度为6~22位字符，且只能是字母与数字组成'
                }),
                validator: (rule, value) => {
                  if (!rule.pattern?.test(value) || !value) {
                    // 更新TabPaneKey
                    setActiveKey('account');
                    return Promise.reject(rule.message);
                  }
                  return Promise.resolve();
                }
              },
            ]}
            transform={(value: any, field: string, object: API.UserCreateDto) => {
              object[field] = Md5.hashStr(value);
              return object;
            }}
          />
          <ProFormText.Password
            label={intl.formatMessage({
              id: 'pages.user.detail.input.confirmpassword',
              defaultMessage: '确认密码'
            })}
            name="confirm-password"
            dependencies={['password']}
            placeholder={intl.formatMessage({
              id: 'pages.user.detail.input.confirmpassword.placeholder',
              defaultMessage: '请再次输入登录密码进行确认'
            })}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  // 更新TabPaneKey
                  setActiveKey('account');
                  return Promise.reject(new Error(intl.formatMessage({
                    id: 'pages.user.detail.input.confirmpassword.rules',
                    defaultMessage: '两次输入的密码不一致,请检查'
                  })));
                },
              }),
            ]}
          />
        </TabPane>}
        {recored?.id !== undefined && <TabPane tab={<><FileProtectOutlined /> 通行证</>} key="assport" forceRender={true}>
          <Divider orientation="left" style={{ marginTop: 0 }} plain>
            <span style={{ marginRight: 5 }}>{intl.formatMessage({
              id: 'pages.user.detail.passport.divider',
              defaultMessage: '全部通行证'
            })}</span>
          </Divider>
          <ProForm.Item name="passports" valuePropName="dataSource"
            noStyle>
            <ProList<API.UserPassportDto>
              showActions="hover"
              showExtra="hover"
              cardProps={{
                bodyStyle: {
                  padding: 0
                },
              }}
              metas={{
                title: {
                  dataIndex: 'account',
                },
                avatar: {
                  render: (_, entity) => handlePassportTypeIcon(entity.typeCode!)
                },
                description: {
                  dataIndex: 'createdTime',
                },
                subTitle: {
                  render: (_, entity) => {
                    return (
                      <Space>
                        <Tag color="blue">{entity.typeName}</Tag>
                      </Space>
                    );
                  },
                },
                actions: {
                  render: (_, entity) => [
                    <Switch key="passport_enable" defaultChecked={entity.enable}
                      checkedChildren="开启"
                      unCheckedChildren="关闭"
                      onChange={(checked) => {
                        console.log('passport_enable', checked, recored.passports);
                        entity.enable = checked;
                      }}
                    />,
                  ],
                },
              }}
            />
          </ProForm.Item>
        </TabPane>}
        <TabPane tab={<><IdcardOutlined /> {intl.formatMessage({
          id: 'pages.user.detail.role',
          defaultMessage: '角色授权'
        })}</>} key="role" forceRender={true}>
          <Divider orientation="left" style={{ marginTop: 0 }} plain>
            <span style={{ marginRight: 5 }}>{intl.formatMessage({
              id: 'pages.user.detail.role.divider',
              defaultMessage: '角色分配'
            })}</span>
            <Tooltip title={intl.formatMessage({
              id: 'pages.user.detail.role.divider.tip',
              defaultMessage: '显示分配与继承的角色'
            })}><InfoCircleOutlined />
            </Tooltip>
          </Divider>
          {roleList.length && <ProForm.Item name="roles"
            style={{
              marginBottom: 0
            }}>
            <CheckCard.Group
              multiple
              size="small"
            // defaultValue={roleList.filter(t => t.isDefault).map(m => m.id!)}
            >
              <Row gutter={10}>
                {roleList.map(({ name, id, hasSeed }) => (<Col key={id} span={roleList.length > 1 ? 12 : 24}>
                  <CheckCard
                    title={<><TagOutlined /> {name} {hasSeed && <Tag color="magenta">{intl.formatMessage({
                      id: 'pages.user.detail.role.card.tags',
                      defaultMessage: '内置'
                    })}</Tag>}</>}
                    value={id}
                    className={styles.roleCard}
                  />
                </Col>))}
              </Row>
            </CheckCard.Group>
          </ProForm.Item>}
        </TabPane>
        <TabPane tab={<><ClusterOutlined /> {intl.formatMessage({
          id: 'pages.user.detail.orgs',
          defaultMessage: '组织机构'
        })}</>} key="orgs" forceRender={true}>
          <Divider orientation="left" style={{ marginTop: 0 }} plain>
            <span style={{ marginRight: 5 }}>{intl.formatMessage({
              id: 'pages.user.detail.orgs.divider',
              defaultMessage: '所属的组织机构'
            })}</span>
          </Divider>
          {treeData.length ? (<ProForm.Item name="orgs" valuePropName="checkedKeys">
            <Tree
              switcherIcon={<DownOutlined />}
              treeData={treeData}
              onCheck={(checkedKeysValue: any) => {
                formRef.current?.setFieldsValue({
                  orgs: checkedKeysValue.checked as string[]
                })
              }}
              checkable
              checkStrictly
              showIcon
              defaultExpandAll
              blockNode />
          </ProForm.Item>) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}

        </TabPane>
      </Tabs>
    </ModalForm>
  )
};

export default DetailViewer;
